<?php


namespace App\Logic\Account\Form;

use App\Core\BaseListForm;
use App\Core\Exception\DefaultException;
use App\Event\Event;
use App\Model\Account\CashoutModel;
use App\Model\Member\MemberModel;
use App\Model\Member\MemberScoreModel;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\ORM\DbManager;

class FinshCashoutForm extends BaseListForm
{
    public $id;
    public $user_id;
    public $payment_content;
    public $_memberModel;
    /**
     * 校验规则 rules
     * @return array[]
     */
    public function rules()
    {
        return [
            'id'    => ['required|numeric', 'id', 'id错误'],
            'user_id' => ['required|numeric', '用户id', '用户id错误'],
            'payment_content' => ['required', '支付凭证', '支付凭证错误'],
        ];
    }
    public function validate()
    {
        //生成验证器，方法自动读取rules方法返回的值数据
        $validator = $this->createValidator();
        if (!($check = $validator->validate($this->getAttributes()))) {
            throw new DefaultException($validator->getError()->__toString(), 600);
        }
        /**通过id获取提现记录*/
        $cashout = CashoutModel::getOne(['id' => $this->id]);
        if(!$cashout){
            throw new DefaultException('提现记录不存在', 600);
        }
        /**判断用户id是否匹配*/
        if($cashout->user_id != $this->user_id){
            throw new DefaultException('用户id不匹配,请核实', 600);
        }
        /**判断当前状态是否为INPROGRESS*/
        if($cashout->cash_state != CashoutModel::INPROGRESS){
            throw new DefaultException('提现记录状态错误', 600);
        }
        return true;
    }

    public function submit()
    {
        $this->validate();
        //插入数据
        DbManager::getInstance()->startTransactionWithCount('write');
        try {
            $cashout = CashoutModel::create()->connection('write')->lockForUpdate()->get($this->id);

            $data = [
                'payment_content' => $this->payment_content,
                'cash_state' => CashoutModel::FINISHED,
                'payment_date' => date('Y-m-d'),
            ];
            CashoutModel::create()->updateData($data, ['id' => $this->id]);

            DbManager::getInstance()->commitWithCount('write');

            $returnData = ['id' => $this->id];
            $result = $this->success($returnData);
            return $result;
        } catch (\Throwable $e) {
            DbManager::getInstance()->rollbackWithCount('write');
            CommonHelper::logException($e, '下单错误');
            throw $e;
        }
    }

}
